"use client";

import * as React from "react";

import { type Alignment } from "@platejs/basic-styles";
import { type DropdownMenuProps } from "@radix-ui/react-dropdown-menu";

import { TextAlignPlugin } from "@platejs/basic-styles/react";
import {
  AlignCenterIcon,
  AlignJustifyIcon,
  AlignLeftIcon,
  AlignRightIcon,
} from "lucide-react";
import { useEditorPlugin, useSelectionFragmentProp } from "platejs/react";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/plate/ui/dropdown-menu";

import { ToolbarButton } from "./toolbar";

const items = [
  {
    icon: AlignLeftIcon,
    value: "left",
  },
  {
    icon: AlignCenterIcon,
    value: "center",
  },
  {
    icon: AlignRightIcon,
    value: "right",
  },
  {
    icon: AlignJustifyIcon,
    value: "justify",
  },
];

export function AlignToolbarButton(props: DropdownMenuProps) {
  const { editor, tf } = useEditorPlugin(TextAlignPlugin);
  const value =
    useSelectionFragmentProp({
      defaultValue: "start",
      getProp: (node) =&gt; node.align,
    }) ?? "left";

  const [open, setOpen] = React.useState(false);
  const IconValue =
    items.find((item) =&gt; item.value === value)?.icon ?? AlignLeftIcon;

  return (
    &lt;DropdownMenu open={open} onOpenChange={setOpen} modal={false} {...props}&gt;
      &lt;DropdownMenuTrigger asChild&gt;
        &lt;ToolbarButton pressed={open} tooltip="Align" isDropdown&gt;
          &lt;IconValue /&gt;
        &lt;/ToolbarButton&gt;
      &lt;/DropdownMenuTrigger&gt;

      &lt;DropdownMenuContent className="min-w-0" align="start"&gt;
        &lt;DropdownMenuRadioGroup
          value={value}
          onValueChange={(value) =&gt; {
            tf.textAlign.setNodes(value as Alignment);
            editor.tf.focus();
          }}
        &gt;
          {items.map(({ icon: Icon, value: itemValue }) =&gt; (
            &lt;DropdownMenuRadioItem
              key={itemValue}
              className="*:first:[span]:hidden pl-2 data-[state=checked]:bg-accent"
              value={itemValue}
            &gt;
              &lt;Icon /&gt;
            &lt;/DropdownMenuRadioItem&gt;
          ))}
        &lt;/DropdownMenuRadioGroup&gt;
      &lt;/DropdownMenuContent&gt;
    &lt;/DropdownMenu&gt;
  );
}
